import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/home/news_list_logic.dart';
import 'package:sports_new/entity/expert/expert_hot_entity.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/home/post_cell.dart';
import 'package:sports_new/view/no_privacy/zixun_cell.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../../widgets/base/qkd_text.dart';
import '../loading/loading_home_widget.dart';

class ZixunPage extends StatefulWidget {
  const ZixunPage({Key? key}) : super(key: key);

  @override
  State<ZixunPage> createState() => _ZixunPageState();
}

class _ZixunPageState extends State<ZixunPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  final id = 'toutiao';
  late final NewsListLogic logic = Get.put(NewsListLogic(), tag: id);
  final visibleKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: Styles.appBar(title: QkdText('资讯'), showLeading: false),
      body: GetBuilder<NewsListLogic>(
          tag: id,
          initState: (state) {
            logic.getResources();
          },
          builder: (logic) {
            return VisibilityDetector(
              key: visibleKey,
              onVisibilityChanged: (info) {
                logic.visible = !info.visibleBounds.isEmpty;
                if (logic.config == null) {
                  logic.getResources();
                }
              },
              child: Container(
                color: Colours.greyF5F7FA,
                child: EasyRefresh(
                  controller: logic.refreshController,
                  footer:
                      Styles.refreshFooter(position: IndicatorPosition.locator),
                  onRefresh: logic.getRefresh,
                  onLoad: logic.loadMore,
                  child: LoadingWidget<bool>(
                    isLoading: logic.newsItems == null,
                    loading: const LoadingHomeWidget(),
                    data: false,
                    child: () => CustomScrollView(
                      // controller: scrollC,
                      slivers: [
                        SliverList(
                          delegate:
                              SliverChildBuilderDelegate((context, index) {
                            final e = logic.newsItems?[index];
                            if (e?.type == 2) {
                              return PostCell(e!);
                            } else {
                              return ZixunCell(
                                e!,
                                inHome: true,
                                classId: logic.config?.infoClassId,
                                afterRoute: update,
                              );
                            }
                          }, childCount: logic.newsItems?.length),
                        ),
                        if (!logic.newsItems.hasValue)
                          SliverToBoxAdapter(
                              child: const NoDataWidget(tip: "暂无资讯")
                                  .sized(height: 400)),
                        const FooterLocator.sliver()
                      ],
                    ),
                  ),
                ),
              ),
            );
          }),
    );
  }

  Widget collectionWidget() {
    return SizedBox(
      width: double.infinity,
      height: 30,
      child: ListView.builder(
        physics: const ClampingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        itemCount: logic.collection.length,
        itemBuilder: (context, index) {
          ResourceEntity entity = logic.collection[index];
          return GestureDetector(
            onTap: () {
              Get.toNamed(Routes.newsList,
                  arguments: entity.content,
                  parameters: {'title': entity.title ?? ''});
            },
            child: Container(
              width: 102,
              height: 30,
              decoration: BoxDecoration(
                  color: Colours.white,
                  border: Border.all(color: Colours.greyEE),
                  borderRadius: BorderRadius.circular(15)),
              padding: const EdgeInsets.symmetric(horizontal: 8),
              margin: EdgeInsets.only(
                  left: index == 0 ? 8 : 0,
                  right: index == logic.collection.length - 1 ? 8 : 8),
              child: Row(
                children: [
                  ClipOval(
                      child: CachedNetworkImage(
                          imageUrl: entity.imgUrl ?? '',
                          width: 16,
                          height: 16,
                          fit: BoxFit.cover)),
                  const SizedBox(width: 2),
                  Expanded(
                    child: QkdText(
                      entity.title ?? '',
                      maxLines: 1,
                    )
                  ),
                  Image.asset(Utils.getImgPath('arrow_right.png'),
                      width: 6, height: 10)
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget hotExpertList() {
    return Styles.card(
        height: 190,
        margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
        padding: const EdgeInsets.only(top: 12, bottom: 16),
        child: Column(
          children: [
            Row(
              children: [
                const SizedBox(width: 12),
                Image.asset(Utils.getImgPath('star.png'), width: 20),
                const SizedBox(width: 4),
                QkdText('关注他们，及时获取赛场信息',
                  fontWeight: FontWeight.w500,
                  fontSize: 15
                ),
                const Spacer(),
                QkdButton(
                    height: 20,
                    widget: Row(children: [
                      QkdText('全部',color: Colours.grey66),
                      const SizedBox(width: 5),
                      Image.asset(Utils.getImgPath('arrow_right.png'),
                          width: 6, height: 10)
                    ]),
                    onPressed: () {
                      Get.toNamed(Routes.expertAll);
                    })
              ],
            ),
            const SizedBox(height: 12),
            Expanded(
              child: ListView.builder(
                physics: const ClampingScrollPhysics(),
                scrollDirection: Axis.horizontal,
                itemCount: logic.hotExpert.length,
                itemBuilder: (context, index) {
                  NewsExpertHotEntity expert = logic.hotExpert[index];
                  return GestureDetector(
                    onTap: () {
                      Get.toNamed(Routes.userPage,
                          arguments: expert.id,
                          parameters: {'type': '2'});
                    },
                    child: Container(
                      width: 100,
                      height: 130,
                      padding: const EdgeInsets.symmetric(horizontal: 8),
                      margin: EdgeInsets.only(
                        left: index == 0 ? 12 : 8,
                        right: index == logic.hotExpert.length - 1 ? 12 : 0
                      ),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colours.greyEE),
                        borderRadius: BorderRadius.circular(4)
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const SizedBox(height: 12),
                          Stack(
                            children: [
                              ClipOval(
                                child: CachedNetworkImage(
                                  imageUrl: expert.logo ?? '',
                                  fit: BoxFit.cover,
                                  width: 52,
                                  height: 52
                                ),
                              ),
                              if ((expert.infoHot ?? 0) >= 1)
                              Positioned(
                                right: 0,
                                bottom: 0,
                                child: Image.asset(
                                  Utils.getImgPath('fire.png'),
                                  width: 16
                                )
                              )
                            ],
                          ),
                          const SizedBox(height: 4),
                          QkdText(expert.name ?? '',
                            maxLines: 1,
                            fontWeight: FontWeight.w500
                          ),
                          const SizedBox(height: 2),
                          QkdText(expert.info ?? '',
                            maxLines: 2,
                            color: Colours.grey99, fontSize: 10
                          )
                        ]
                      ),
                    ),
                  );
                },
              ),
            )
          ],
        ));
  }
}
